﻿/* $RCSFile: ChildControlHelper.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/Helpers/ChildControlHelper.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:28  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

namespace AddonNice.Web.UI
{
    public static class ChildControlHelper
    {
		public static Control FindControlRecursive(Control searcher, string ID)
		{
			//First search the same naming container:
			Control searched = searcher.NamingContainer.FindControl(ID);
			if (searched != null)
			{
				return searched;
			}

			Control root;
			if (searcher.Page.Master != null)
			{
				root = searcher.Page.Master;
			}
			else
			{
				root = searcher.Page;
			}

			Control control = root.FindControl(ID);
			if (control != null)
			{
				return control;
			}

            control = searcher.Page.FindControl(ID);
            if (control != null)
            {
                return control;
            }

			if (searcher.UniqueID == ID || searcher.ClientID == ID)
			{
				return searcher;
			}

			return FindControlRecursive(ID, root);
		}

		public static Control FindControlRecursive(string ID, Control root)
		{
			Control control = null;

            if (root is DataBoundControl && !root.Visible) return control;

			foreach (Control ctrl in root.Controls)
			{
				if (ctrl is INamingContainer && ctrl.FindControl(ID) != null)
				{
					control = ctrl.FindControl(ID);
					break;
				}
				else if (ctrl.HasControls())
				{
					control = FindControlRecursive(ID, ctrl);
					if (control != null && (control.UniqueID == ID || control.ID == ID))
					{
						break;
					}
				}
			}
			return control;
		}
	}
}

